import { keepAliveViews } from './cache';

/**
 * @description: 获取需要缓存的页面
 * @param {any} to
 * @param {any} from
 * @param {any} arr
 * @return {*}
 */
export const getKeepAliveViews = (to: any, from: any, arr: any) => {
    const {
        meta: { code: toCode = '' },
        path: toPath = '',
        name: toName
    } = to;
    const {
        meta: { code: fromCode = '' },
        path: fromPath = '',
        name: fromName
    } = from;
    if (!toCode || !fromCode) return arr;
    keepAliveViews.forEach(item => {
        const { cachePageCode, cacheType, routePageCodes } = item;
        if (cachePageCode === fromCode && cachePageCode === toCode) {
            if (arr.includes(fromName) && arr.includes(toName)) {
                arr = arr.filter((item: any) => item !== fromName);
            }
            return false;
        }
        if (cachePageCode === fromCode) {
            let flag = false;
            switch (cacheType) {
                case 0:
                    flag = true;
                    break;
                case 1:
                    flag = toPath.includes(fromPath);
                    break;
                case 2:
                    flag = routePageCodes.includes(toCode);
                    break;
                case 3:
                    flag = toPath.includes(fromPath) || routePageCodes.includes(toCode);
            }
            if (flag) {
                if (!arr.includes(fromName)) {
                    arr.push(fromName);
                }
            } else {
                if (arr.includes(fromName)) {
                    arr = arr.filter((item: any) => item !== fromName);
                }
            }
            return flag;
        }
        if (cachePageCode === toCode) {
            let flag = false;
            switch (cacheType) {
                case 0:
                    flag = true;
                    break;
                case 1:
                    flag = fromPath.includes(toPath);
                    break;
                case 2:
                    flag = routePageCodes.includes(fromCode);
                    break;
                case 3:
                    flag = fromPath.includes(toPath) || routePageCodes.includes(fromCode);
            }
            if (flag) {
                if (!arr.includes(toName)) {
                    arr.push(toName);
                }
            } else {
                if (arr.includes(toName)) {
                    arr = arr.filter((item: any) => item !== toName);
                }
            }
            return flag;
        }
        return false;
    });
    return arr;
};
